local loadfile = loadfile
local setfenv = setfenv

local env = {}

ffi = require "ffi" -- Need to load explicitly

do
	local mod, err = loadfile "module.lua"
	if not mod then
		error("loadfile error: " .. err)
	end
	mod(env)
end

env._G = env

for _,g in ipairs({
	"assert", "ipairs", "pairs", "next", "pcall", "tonumber", "tostring",
	"type", "unpack", "print", "error", -- TODO: Is error bad?
	"coroutine", "string", "math", "table", -- Don't care about table modification
	"bit", "loadstring",
	"load", -- TEMP, although it cannot be used for loading bytecode in luajit2, so it's safe for the moment
	"io", -- TEMP
	"test", "jit",

	-- TODO: Make sure metatables cannot leak anything bad, using __metatable if necessary.
	-- We don't care about the sandbox being able to modify metatables.
	"getmetatable", "setmetatable",
	"require", "dofile",
	"ffi" --TEMP
	}) do
	env[g] = _G[g]
end

--env.sound = _G["portaudio"]
--env.random = _G["random"]
--env.system = _G["system"]
--env.mathe = _G["fdlibm"]

--env.os = {clock = os.clock}

local strict = env.require "strict"

strict.make_strict(_G)
strict.make_strict(env)

local function error_handler(err)

--[[
	print("Error:", err)

	for i=1,10 do
		local info = debug.getinfo(i)
		if not info then
			break
		end

		print(info.name .. ":" .. info.currentline .. ": " .. info.short_src)
	end]]

	print(debug.traceback(err, 2))
end

local function sandbox(f)
	setfenv(f, env)

	print("Begin sandbox")
	xpcall(f, error_handler)
	print("End sandbox")
end

local args = ...

print("Argument count: " .. #args)

sandbox(function()
	--env.dofile "gfxtest.lua"
	--env.dofile "gametest.lua"
	--env.dofile "nettest.lua"
	--env.dofile "synctest.lua"
	--env.dofile "drawtest.lua"
	--env.dofile "bitstreamtest.lua"
	--env.dofile "functest.lua"
	--env.dofile "streamstest.lua"
	--env.dofile "randomtest.lua"
	--env.dofile "guitest.lua"
	--env.dofile "fluatest.lua"
	env.dofile(args[2])
	--gfx_test(args)
	--net_test()
	--draw_test()
end)